import 'dart:io';
import 'package:sqflite/sqflite.dart';
import '../models/emotion_record.dart';
import '../services/database_service.dart';
import 'media_repository.dart';

/// 媒体文件数据仓库实现
/// Media file repository implementation
class MediaRepositoryImpl implements MediaRepository {

  final DatabaseService _databaseService = DatabaseService();

  @override
  Future<List<MediaFile>> getMediaFilesByRecordId(String recordId) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      'media_files',
      where: 'record_id = ?',
      whereArgs: [recordId],
      orderBy: 'created_at ASC',
    );
    
    return List.generate(maps.length, (i) {
      return MediaFile.fromJson(maps[i]);
    });
  }

  @override
  Future<String> insertMediaFile(MediaFile mediaFile) async {
    final db = await _databaseService.database;
    await db.insert(
      'media_files',
      mediaFile.toJson(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
    return mediaFile.id;
  }

  @override
  Future<void> deleteMediaFile(String id) async {
    final db = await _databaseService.database;
    
    // 首先获取文件信息以删除物理文件
    // First get file info to delete physical file
    final List<Map<String, dynamic>> maps = await db.query(
      'media_files',
      where: 'id = ?',
      whereArgs: [id],
      limit: 1,
    );
    
    if (maps.isNotEmpty) {
      final mediaFile = MediaFile.fromJson(maps.first);
      
      // 删除物理文件
      // Delete physical file
      try {
        final file = File(mediaFile.filePath);
        if (await file.exists()) {
          await file.delete();
        }
      } catch (e) {
        // 忽略文件删除错误，继续删除数据库记录
        // Ignore file deletion errors, continue to delete database record
        print('Error deleting file: $e');
      }
    }
    
    // 删除数据库记录
    // Delete database record
    await db.delete(
      'media_files',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  @override
  Future<void> deleteMediaFilesByRecordId(String recordId) async {
    final db = await _databaseService.database;
    
    // 首先获取所有相关的媒体文件
    // First get all related media files
    final mediaFiles = await getMediaFilesByRecordId(recordId);
    
    // 删除所有物理文件
    // Delete all physical files
    for (final mediaFile in mediaFiles) {
      try {
        final file = File(mediaFile.filePath);
        if (await file.exists()) {
          await file.delete();
        }
      } catch (e) {
        // 忽略文件删除错误
        // Ignore file deletion errors
        print('Error deleting file: $e');
      }
    }
    
    // 删除数据库记录
    // Delete database records
    await db.delete(
      'media_files',
      where: 'record_id = ?',
      whereArgs: [recordId],
    );
  }

  @override
  Future<int> getTotalMediaFileSize() async {
    final db = await _databaseService.database;
    
    final List<Map<String, dynamic>> maps = await db.query(
      'media_files',
      columns: ['file_path'],
    );
    
    int totalSize = 0;
    
    for (final map in maps) {
      final filePath = map['file_path'] as String;
      try {
        final file = File(filePath);
        if (await file.exists()) {
          final stat = await file.stat();
          totalSize += stat.size;
        }
      } catch (e) {
        // 忽略文件访问错误
        // Ignore file access errors
        print('Error accessing file: $e');
      }
    }
    
    return totalSize;
  }

  @override
  Future<void> cleanupInvalidMediaFiles() async {
    final db = await _databaseService.database;
    
    final List<Map<String, dynamic>> maps = await db.query(
      'media_files',
      columns: ['id', 'file_path'],
    );
    
    final List<String> invalidIds = [];
    
    // 检查每个文件是否存在
    // Check if each file exists
    for (final map in maps) {
      final id = map['id'] as String;
      final filePath = map['file_path'] as String;
      
      try {
        final file = File(filePath);
        if (!await file.exists()) {
          invalidIds.add(id);
        }
      } catch (e) {
        // 如果无法访问文件，也认为是无效的
        // If file cannot be accessed, also consider it invalid
        invalidIds.add(id);
      }
    }
     // 批量删除无效的媒体文件记录
    // Batch delete invalid media file records
    if (invalidIds.isNotEmpty) {
      final batch = db.batch();
      
      for (final id in invalidIds) {
        batch.delete(
          'media_files',
          where: 'id = ?',
          whereArgs: [id],
        );
      }
      
      await batch.commit();
    }
  }
  }





  